from fastapi import APIRouter, HTTPException, Depends, Header
from typing import Optional
import logging
from datetime import datetime, timezone

from services.file_service import FileService
from models.schemas import ExperimentRequest, ExperimentResponse, ResponseBase
from config import settings

router = APIRouter()
logger = logging.getLogger("mobox-server.api")

# 简单的认证检查（可选）
async def verify_token(authorization: Optional[str] = Header(None)):
    # 暂时不检查认证
    return True

@router.post("/experiment/resource", response_model=ResponseBase[ExperimentResponse], 
             summary="生成实验资源URL", description="根据用户ID、实验ID和课程名称生成资源URL")
async def get_experiment_resource(request: ExperimentRequest):
    logger.info(f"接收到请求: {request.model_dump()}")
    
    try:
        # 1. 检查并创建用户、课程、实验目录
        file_service = FileService()
        experiment_dir = file_service.ensure_experiment_directory(
            user_id=request.user_id,
            course_name=request.course_name,
            experiment_id=request.experiment_id
        )
        
        # 2. 构建服务访问URL，使用本机IP而不是localhost
        service_url = f"http://{settings.HOST_IP}:{settings.JUPYTER_PORT}/?folder={experiment_dir}"
        
        # 3. 返回成功响应
        return ResponseBase[ExperimentResponse](
            status_code=200,
            data=ExperimentResponse(
                url=service_url,
                last_time=datetime.now(timezone.utc).isoformat()
            ),
            message="资源URL生成成功"
        )
        
    except ValueError as e:
        # 处理参数错误
        logger.error(f"请求参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        # 处理其他错误
        logger.error(f"处理请求时发生错误: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"服务器内部错误: {str(e)}") 